window.onload = function () {
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  // 离屏canvas

  const offscreenCanvas = document.createElement("canvas");
  const offscreenContext = offscreenCanvas.getContext("2d");

  const data = [
    {
      url: "./imgs/1.jpg",
      width: 500,
      height: 500,
    },
  ];

  offscreenCanvas.width = canvas.width;
  offscreenCanvas.height = canvas.height;

  const scaleSlider = document.getElementById("scaleSlider"),
    scaleOurput = document.getElementById("scaleOutput");
  let scale = 1.0;

  const image = new Image();

  function drawScaled() {
    const w = canvas.width,
      h = canvas.height,
      sw = scale * w,
      sh = scale * h;
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(
      offscreenCanvas,
      0,
      0,
      offscreenCanvas.width,
      offscreenCanvas.height,
      w / 2 - sw / 2,
      h / 2 - sh / 2,
      sw,
      sh
    );
  }
  function drawScaleText(value) {
    const text = parseFloat(value).toFixed(2);
    scaleOurput.innerText = text;
  }

  function drawWatermark(context) {
    const lineOne = "CopyRight";
    const lineTwo = "Yeahmobi";
    const fontHeight = 40;
    let textMetrics = null;
    context.save();
    context.fillStyle = "rgba(100,140,230,0.5)";
    context.strokeStyle = "yellow";
    context.shadowColor = "rgba(50,50,50,1.0)";
    context.shadowOffsetX = 5;
    context.shadowOffsetY = 5;
    context.shadowBlur = 10;

    context.font = fontHeight + "px Arial";
    textMetrics = context.measureText(lineOne);
    console.log(textMetrics);
    context.translate(canvas.width / 2, canvas.height / 2);
    context.fillText(lineOne, -textMetrics.width / 2, -20);
    context.strokeText(lineOne, -textMetrics.width / 2, -20);

    textMetrics = context.measureText(lineTwo);
    context.fillText(lineTwo, -textMetrics.width / 2, fontHeight - 20);
    context.strokeText(lineTwo, -textMetrics.width / 2, fontHeight - 20);

    context.restore();
  }

  image.src = data[0].url;
  image.onload = function () {
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    offscreenContext.drawImage(
      image,
      0,
      0,
      offscreenCanvas.width,
      offscreenCanvas.height
    );

    drawWatermark(context);
    drawWatermark(offscreenContext);
  };
  scaleSlider.onchange = function (e) {
    scale = e.target.value;

    drawScaleText(scale);
    drawScaled();
  };
};
